/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */

package org.apache.http.examples.client;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.util.NetUtils;

import com.swf.seed.base.SdCharset;
import com.swf.seed.base.SystemContants;
import com.swf.seed.regex.PatternUtils;
import com.swf.seed.triutil.lang.SdNetUtils;

/**
 * This example demonstrates the use of the {@link ResponseHandler} to simplify
 * the process of processing the HTTP response and releasing associated resources.
 */
public class ClientWithResponseHandler {

    public final static void main(String[] args) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet("http://boafanx.tabboa.com/boafanx-ss/");

            System.out.println("Executing request " + httpget.getRequestLine());

            // Create a custom response handler
            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

                public String handleResponse(
                        final HttpResponse response) throws ClientProtocolException, IOException {
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {
                        HttpEntity entity = response.getEntity();
                        return entity != null ? EntityUtils.toString(entity) : null;
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }

            };
            String responseBody = httpclient.execute(httpget, responseHandler);
            System.out.println("----------------------------------------");
            List<String> list = PatternUtils.matchedList(responseBody,".+");
            List<String> newList= new ArrayList<String>();
            for (String s:list){
            	s = s.trim().replace("</em>", "_").replace("<em>", "_");
            	if (s.startsWith("\"")&&s.contains("\":")){
            		newList.add(s);
            	}
            }
            int size = newList.size()/6;
            List<String> jsonTxt = new ArrayList<String>();
            String ip = null;
            String port = null;
            String ipLine;
            String portLine;
            for (int i=0;i<size;i++){
            	StringBuilder sb = new StringBuilder("{").append(SystemContants.LINE_SEPARATOR);
            	for (int j=0;j<6;j++){
            		int number = i*6+j;
            		if (j==0){
            			ipLine = newList.get(number);
            			ip = PatternUtils.matchedFirstOne(ipLine, "\\d.+\\d");
            		}else if (j==1){
            			portLine = newList.get(number);
            			port = PatternUtils.matchedFirstOne(portLine, "\\d+");
            		}
            		
            		sb.append(newList.get(number)).append(SystemContants.LINE_SEPARATOR);
            	}
            	sb.append("}");
            	boolean flag = SdNetUtils.telnet(ip, port);
            	if (flag){
            		System.out.println(String.format("telnet %s %s succeed",ip,port));
            		System.out.println(sb.toString());
            		FileWriter fileWriter = new FileWriter((i==0?"":i)+"config.json");
            		fileWriter.write(sb.toString());
            		fileWriter.flush();
            	}else{
            		System.out.println(String.format("telnet %s %s failed",ip,port));
            	}
            }
        } finally {
            httpclient.close();
        }
    }

}
